package com.ms.p2p.plugin.payment.fuyou;


import com.ms.common.mapper.JsonMapper;
import com.ms.common.utils.MsDateUtils;
import com.ms.p2p.entity.account.AccountRecharge;
import com.ms.p2p.entity.system.PayMethod;
import com.ms.p2p.plugin.payment.AbstractPaymentPlugin;
import com.ms.p2p.plugin.payment.IPaymentEvent;
import com.ms.p2p.plugin.payment.fuyou.util.FyRechargeB2CBean;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class FuyouPayment extends AbstractPaymentPlugin implements IPaymentEvent {


    @Override
    public void register() {

    }

    @Override
    public String onPay(Integer userId, BigDecimal money, HashMap other,HttpServletRequest request) throws Exception {
        PayMethod payment = payMethodService.findById(getId());
        AccountRecharge rechargeOrder = BuildReCharge(userId, money, payment);
        FyRechargeB2CBean b2c = new FyRechargeB2CBean();
        b2c.setMchnt_cd(payMethodValueService.findByName("fuyou.mchnt_cd").getParamValue());
        b2c.setOrder_id(rechargeOrder.getTrade_no());
        b2c.setOrder_amt(rechargeOrder.getMoney().multiply(new BigDecimal(100)));
        b2c.setOrder_pay_type("B2C");
        String weburl = settingService.findValueByCode("weburl");
        String urlStr = "http://" + weburl + "";
        String noticeurl =  payMethodValueService.findByName("fuyou.b2cretutn").getParamValue();
        String backurl =  payMethodValueService.findByName("fuyou.b2cnotify").getParamValue();
        noticeurl = urlStr + noticeurl;
        backurl = urlStr + backurl;
        b2c.setPage_notify_url(noticeurl);
        b2c.setBack_notify_url(backurl);
        b2c.setOrder_valid_time("10m");
        b2c.setIss_ins_cd(other.get("bank_code").toString());
        b2c.setVer("1.0.1");
        String signStr = b2c.getMchnt_cd() +"|"+ b2c.getOrder_id() +"|"+ b2c.getOrder_amt() +"|"+ b2c.getOrder_pay_type()
                +"|"+ b2c.getPage_notify_url() +"|"+ b2c.getBack_notify_url() +"|"+ b2c.getOrder_valid_time() +"|"+ b2c.getIss_ins_cd()
                +"|"+ "" +"|"+ "" +"|"+ "" +"|"+ b2c.getVer() +"|"+ payMethodValueService.findByName("fuyou.b2ckey").getParamValue();
        b2c.setMd5(MD5Encode(signStr));
        LinkedHashMap map = new LinkedHashMap();
        map.put("mchnt_cd",payMethodValueService.findByName("fuyou.mchnt_cd").getParamValue());
        map.put("order_id",rechargeOrder.getTrade_no());
        map.put("order_amt",rechargeOrder.getMoney().multiply(new BigDecimal(100)));
        map.put("order_pay_type","B2C");
        map.put("page_notify_url",noticeurl);
        map.put("back_notify_url",backurl);
        map.put("order_valid_time","10m");
        map.put("iss_ins_cd",other.get("bank_code").toString());
        map.put("ver","1.0.1");
        map.put("md5",MD5Encode(signStr));
        logger.info("网银充值请求："+ JsonMapper.toJsonString(map));

        return buildPostRequest(map,  payMethodValueService.findByName("fuyou.b2curl").getParamValue(),request);
    }

    @Override
    public String onReturn(HttpServletRequest request) throws Exception {
        logger.info("——————————————富友网银支付异步回调开始"+ MsDateUtils.getTimeToday());

        request.setCharacterEncoding("UTF-8");
        String mchnt_cd = nvl(request.getParameter("mchnt_cd"));
        String order_id = nvl(request.getParameter("order_id"));
        String order_date = nvl(request.getParameter("order_date"));
        String order_amt = nvl(request.getParameter("order_amt"));
        String order_st =nvl(request.getParameter("order_st"));
        String txn_cd = nvl(request.getParameter("txn_cd"));
        String order_pay_code = nvl(request.getParameter("order_pay_code"));
        String order_pay_error = nvl(request.getParameter("order_pay_error"));
        String resv1 = nvl(request.getParameter("resv1"));
        String fy_ssn = nvl(request.getParameter("fy_ssn"));
        String md5 = nvl(request.getParameter("md5"));
        String mchnt_key =payMethodValueService.findByName("fuyou.b2ckey").getParamValue();  //32位的商户密钥

        String signDataStr = mchnt_cd + "|" + order_id + "|" +
                order_date + "|" + order_amt + "|" + order_st + "|" + order_pay_code + "|" + order_pay_error + "|" + resv1 + "|" + fy_ssn + "|" + mchnt_key;

        // 验证签名是否正常
        String sign = MD5Encode(signDataStr);
        String out_trade_no = order_id;
      //  AccountRecharge recharge = rechargeService.(out_trade_no);
        if ("0000".equals(order_pay_code)) {
            if (sign.equals(md5)) {
                String result =  OnlineReturn(out_trade_no, "在线网银充值-富有支付");
                logger.info("——————————————富友网银支付异步回调成功");
                return "SUCCESS";


            } else {

                logger.info("——————————————富友网银支付异步回调失败，错误原因：验签失败");
            }
        } else {

            //  recharge.setRemark("充值失败,错误原因：" + order_pay_error);
            logger.info("——————————————富友网银支付异步回调失败，错误原因："+order_pay_error);
        }
        return null;
    }

    @Override
    public String getTradeNo(Map<String, String> params) throws Exception {
        return null;
    }

    @Override
    public String getType() {
        return "1";
    }

    @Override
    //id需要与paymethod id一样
    public String getId() {
        return "54";
    }

    @Override
    //名称需要与包明一样
    public String getName() {
        return "fuyou";
    }

    @Override
    public String getVersion() {
        return "1.0.0";
    }

    @Override
    public String getAuthor() {
        return "daimajia";
    }

    @Override
    public void perform(Object... params) {

    }

    public static String MD5Encode(String origin) {
        origin = origin.trim();
        String resultString = null;

        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes("UTF-8")));
        } catch (Exception var3) {
            ;
        }

        return resultString;
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();

        for(int i = 0; i < b.length; ++i) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if(b < 0) {
            n = b + 256;
        }

        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String nvl(String aStr) {
        if (aStr == null || "null".equals(aStr.trim())) {
            return "";
        } else {
            return aStr.trim().toString();
        }
    }
}
